package com.jeesite.modules.vip.web;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jeesite.common.idgen.IdGenerate;
import com.jeesite.modules.sys.entity.*;
import com.jeesite.modules.vip.entity.Project;
import com.jeesite.modules.vip.entity.VipUser;
import com.jeesite.modules.vip.service.ProjectService;
import com.jeesite.modules.vip.service.VipUserService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.utils.excel.annotation.ExcelField.Type;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.service.PostService;
import com.jeesite.modules.sys.service.RoleService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;

/**
 * @author apple
 */
@Controller
@RequestMapping(value = "${adminPath}/vip/agent")
public class AgentController extends BaseController {

	@Autowired
	private EmpUserService empUserService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private PostService postService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private VipUserService vipUserService;

	@ModelAttribute
	public EmpUser get(String userCode, boolean isNewRecord) {
		return empUserService.get(userCode, isNewRecord);
	}
	
	@RequiresPermissions("vip:agent:view")
	@RequestMapping(value = "list")
	public String list(EmpUser empUser, Model model) {
		// 获取岗位列表
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		//默认正常状态的用户
		empUser.setStatus(StringUtils.isNotBlank(empUser.getStatus()) ? empUser.getStatus() : User.STATUS_NORMAL);
		model.addAttribute("empUser", empUser);
		if(UserUtils.getCache("deviceType") != null && "mobile".equals(UserUtils.getCache("deviceType"))){
			return "modules/mobile/agentList";
		}
		return "modules/vip/agentList";
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<VipUser> listData(VipUser empUser, Boolean isAll, HttpServletRequest request, HttpServletResponse response) {
		Page<VipUser> page = vipUserService.findPage(new Page<VipUser>(request, response), empUser);
		return page;
	}

	@RequiresPermissions("vip:agent:view")
	@RequestMapping(value = "form")
	public String form(EmpUser empUser, String op, Model model) {

		Employee employee = empUser.getEmployee();

		// 设置默认的部门
		if (StringUtils.isBlank(employee.getCompany().getCompanyCode())) {
			employee.setCompany(EmpUtils.getCompany());
		}
		
		// 设置默认的公司
		if (StringUtils.isBlank(employee.getOffice().getOfficeCode())) {
			employee.setOffice(EmpUtils.getOffice());
		}
		
		// 获取岗位列表
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		
		// 获取当前用户所拥有的岗位
		if (StringUtils.isNotBlank(employee.getEmpCode())){
			employee.setEmployeePostList(employeeService.findEmployeePostList(employee));
		}

		//获取项目列表
		List<Project> projectList = projectService.findList(new Project());
		model.addAttribute("projectList", projectList);

		// 获取当前用户所拥有的项目
		if (StringUtils.isNotBlank(employee.getEmpCode())){
			employee.setAgentProjectList(employeeService.findAgentProjectList(employee));
		}
		//新增的用户默认选中所有项目
		if(!StringUtils.isNotBlank(employee.getEmpCode())){
			List<AgentProject> agentProjectList = new ArrayList<>();
			for(Project item : projectList){
				AgentProject agentProject = new AgentProject();
				agentProject.setProjectId(item.getId());
				agentProjectList.add(agentProject);
			}
			employee.setAgentProjectList(agentProjectList);
		}
		// 获取当前编辑用户的角色和权限
		if (StringUtils.inString(op, Global.OP_AUTH) ||StringUtils.inString(op, Global.OP_EDIT)) {
			// 获取当前用户所拥有的角色
			Role role = new Role();
			role.setUserCode(empUser.getUserCode());
			model.addAttribute("roleList", roleService.findListByUserCode(role));
		}
		// 操作类型：add: 全部； edit: 编辑； auth: 授权
		model.addAttribute("op", op);
		model.addAttribute("empUser", empUser);
		return "modules/vip/agentForm";
	}

	@RequiresPermissions(value={"vip:agent:edit","vip:agent:authRole"}, logical=Logical.OR)
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated EmpUser empUser, String oldLoginCode, String op, HttpServletRequest request) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!Global.TRUE.equals(userService.checkLoginCode(oldLoginCode, empUser.getLoginCode()))) {
			return renderResult(Global.FALSE, text("保存用户失败，登录账号''{0}''已存在", empUser.getLoginCode()));
		}
		if (StringUtils.inString(op, Global.OP_ADD, Global.OP_EDIT)
				&& UserUtils.getSubject().isPermitted("vip:agent:edit")){
			//若是新用户则设置empUser用户编号
			empUser.getEmployee().setEmpCode(empUser.getIsNewRecord() ? IdGenerate.uuid() : empUser.getEmployee().getEmpCode());
			empUserService.save(empUser);
            userService.saveAuth(empUser);
		}
		return renderResult(Global.TRUE, text("保存用户''{0}''成功", empUser.getUserName()));
	}

	/**
	 * 导出用户数据
	 */
	@RequiresPermissions("vip:agent:view")
	@RequestMapping(value = "exportData")
	public void exportData(EmpUser empUser, Boolean isAll, HttpServletResponse response) {
		empUser.getEmployee().getOffice().setIsQueryChildren(true);
		empUser.getEmployee().getCompany().setIsQueryChildren(true);
		if (!(isAll != null && isAll)){
			empUserService.addDataScopeFilter(empUser, UserDataScope.CTRL_PERMI_MANAGE);
		}
		List<EmpUser> list = empUserService.findList(empUser);
		String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("用户数据", EmpUser.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}

	/**
	 * 下载导入用户数据模板
	 */
	@RequiresPermissions("vip:agent:view")
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response) {
		EmpUser empUser = new EmpUser();
		User user = UserUtils.getUser();
		if (User.USER_TYPE_EMPLOYEE.equals(user.getUserType())){
			empUser = empUserService.get(user.getUserCode());
		}else{
			BeanUtils.copyProperties(user, empUser);
		}
		List<EmpUser> list = ListUtils.newArrayList(empUser);
		String fileName = "用户数据模板.xlsx";
		try(ExcelExport ee = new ExcelExport("用户数据", EmpUser.class, Type.IMPORT)){
			ee.setDataList(list).write(response, fileName);
		}
	}

	
	/**
	 * 停用用户
	 * @param empUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "disable")
	public String disable(EmpUser empUser) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (empUser.getCurrentUser().getUserCode().equals(empUser.getUserCode())) {
			return renderResult(Global.FALSE, text("停用用户失败，不允许停用当前用户"));
		}
		empUser.setStatus(User.STATUS_DISABLE);
		userService.updateStatus(empUser);
		return renderResult(Global.TRUE, text("停用用户''{0}''成功", empUser.getUserName()));
	}
	
	/**
	 * 启用用户
	 * @param empUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "enable")
	public String enable(EmpUser empUser) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		empUser.setStatus(User.STATUS_NORMAL);
		userService.updateStatus(empUser);
		return renderResult(Global.TRUE, text("启用用户''{0}''成功", empUser.getUserName()));
	}
	
	/**
	 * 密码重置
	 * @param empUser
	 * @return
	 */
	@RequiresPermissions("vip:agent:resetpwd")
	@RequestMapping(value = "resetpwd")
	@ResponseBody
	public String resetpwd(EmpUser empUser) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		userService.updatePassword(empUser.getUserCode(), null);
		return renderResult(Global.TRUE, text("重置用户''{0}''密码成功", empUser.getUserName()));
	}

	/**
	 * 删除用户
	 * @param empUser
	 * @return
	 */
	@RequiresPermissions("vip:agent:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(EmpUser empUser) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (empUser.getCurrentUser().getUserCode().equals(empUser.getUserCode())) {
			return renderResult(Global.FALSE, text("删除用户失败，不允许删除当前用户"));
		}
		if(User.STATUS_NORMAL.equals(empUser.getStatus())){
			return renderResult(Global.FALSE, text("删除用户失败，需要停用用户才能删除用户!"));
		}
		empUserService.delete(empUser);
		return renderResult(Global.TRUE, text("删除用户'{0}'成功", empUser.getUserName()));
	}

	@RequestMapping(value = "deviceType",method = RequestMethod.GET)
	@ResponseBody
	public String deviceType(@RequestParam String deviceType){
		UserUtils.putCache("deviceType",deviceType);
		return renderResult(Global.TRUE,"deviceType:"+deviceType);
	}
}
